package com.ruicar.afs.jobadmin.core.util;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * The type JacksonUtil
 * <p>Description: </p>
 *
 * @author Fzero
 * @version 1.0
 * @date Created on 2020.06.13 14:17:08
 * @since 1.0
 */
public class JacksonUtil {
    /**
     * Logger
     * <p>Description: </p>
     */
    private static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);

    /**
     * Object mapper
     * <p>Description: </p>
     */
    private final static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * Gets instance *
     *
     * @return the instance
     */
    public static ObjectMapper getInstance() {
        return objectMapper;
    }

    /**
     * Write value as string string
     *
     * @param obj obj
     * @return the string
     */
    public static String writeValueAsString(Object obj) {
        try {
            return getInstance().writeValueAsString(obj);
        } catch (JsonGenerationException e) {
            logger.error(e.getMessage(), e);
        } catch (JsonMappingException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * Read value t
     *
     * @param <T>     parameter
     * @param jsonStr json str
     * @param clazz   clazz
     * @return the t
     */
    public static <T> T readValue(String jsonStr, Class<T> clazz) {
        try {
            return getInstance().readValue(jsonStr, clazz);
        } catch (JsonParseException e) {
            logger.error(e.getMessage(), e);
        } catch (JsonMappingException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * Read value t
     *
     * @param <T>              parameter
     * @param jsonStr          json str
     * @param parametrized     parametrized
     * @param parameterClasses parameter classes
     * @return the t
     */
    public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) {
        try {
            JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses);
            return getInstance().readValue(jsonStr, javaType);
        } catch (JsonParseException e) {
            logger.error(e.getMessage(), e);
        } catch (JsonMappingException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}
